import json
from pathlib import Path
from zyjkit.print.zprint import zprint

sort = 0
def transform(perm):
    global sort
    key = (perm["href"].replace("/", ":")).lower().strip() if "href" in perm else None
    if key is None:
        return None
    

    key = "admin:" + key

    sort = sort + 1
    dic = {}
    dic[key] = {
        "code": key,
        "name": perm["title"],
        "icon": perm["icon"],
        "is_menu": True,
        "sort": sort,
    }
    return {key: dic[key]}


def process(permissions):
    dic = {}
    for perm in permissions:
        if "children" in perm:
            children = process(perm["children"])
            dic.update(children)
            # 可能没有 href，则判断 children 中最多的 code 的前缀作为 code ，如a:b:c,则父级a:b的个数，最多的作为父级
            if 'href' not in perm or not perm['href'] or perm['href'] == "javascript:;":
                maybe = {}
                for c in children.keys():
                    cs = c.split(":")
                    cs.pop()
                    k = ":".join(cs)
                    maybe[k] = maybe.get(k, 0) + 1
                maybe_code = max(maybe.items(), key=lambda x: x[1])[0]
                perm['href'] = maybe_code.replace("admin:", '').replace(":", "/")

        perm = transform(perm)
        if perm is not None:
            dic.update(perm)
    return dic


if __name__ == "__main__":

    rpath = Path(r"data\menus.json")
    wpath = Path(r"data\permissions.json")

    text = rpath.read_text(encoding="utf-8")

    data = json.loads(text)

    wpath.write_text(
        json.dumps(process(data), ensure_ascii=False, indent=2), encoding="utf-8"
    )

    zprint({
        "success": True,
        "message": "处理完成",
        "total": len(data),
    })

